package com.wandian.weather.mvvm.weatherhome;

import android.app.Application;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.mylib.libcore.AppContext;
import com.mylib.libcore.mvvm.BaseViewModel;
import com.mylib.libcore.utils.ACacheUtil;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.RetrofitUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.weather.bean.SSDataBean;
import com.wandian.weather.bean.ShenshaBean;
import com.wandian.weather.bean.WeatherInformationBean;
import com.wandian.weather.bean.YJDataBean;
import com.wandian.weather.bean.YijiBean;
import com.wandian.weather.data.BaseAppApi;
import com.wandian.weather.tools.JmTools;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author Administrator
 * @date 2019/12/16-13:32
 * @description FragmentHomeViewModel
 **/
public class FragmentWeatherHomeViewModel extends BaseViewModel {

    public MutableLiveData<WeatherInformationBean> weatherInformationBean = new MutableLiveData<>();
    private Retrofit retrofit;
    private BaseAppApi request;
    private String lat;
    private String lng;
    private LinearLayout loadView;
    public FragmentWeatherHomeViewModel(@NonNull Application application) {
        super(application);
    }
    //国内天气
    public void getWeatherData(String lat , String lng, LinearLayout loadView){
        try {
            this.lat =lat;
            this.lng =lng;
            this.loadView =loadView;
            if(UIUtils.isFastClick() && !UIUtils.isEmpty(AppContext.getInstance().getAppPreferencesHelper().getKeyValue("weather_json")))return;
            retrofit = RetrofitUtil.createWeatherRetrofit();
            //创建网络请求接口实例
            request = retrofit.create(BaseAppApi.class);
            HashMap<String, String> hashMap = new HashMap<>();
            //其他参数
            hashMap.put("service","Tianqi.Index");
            hashMap.put("lng",lng);
            hashMap.put("air","1");
            hashMap.put("hour24","1");
            hashMap.put("weather30","15");
            hashMap.put("yesterday","1");
            hashMap.put("outline","1");
            hashMap.put("precipitation_2h","1");
            hashMap.put("lat",lat);
            hashMap.put("need_city","1");
            hashMap.put("lifeindex","1");
            hashMap.put("nl","1");
            hashMap.put("wind","1");
            //公用参数
            hashMap.put("os","1");
            hashMap.put("pid","4");
            hashMap.put("version","6.5.4");

            Log.d("weather_req",JsonUtil.toJson(hashMap));
            Call<Object> call = request.getWeatherData(JmTools.encryptParams(hashMap, "Tianqi.Index"));
            //发送网络请求(异步)
            call.enqueue(new Callback<Object>() {
                @Override
                public void onResponse(Call<Object> call, Response<Object> response) {
                    if(UIUtils.isEmpty(response.body()))return;
                    Log.d("getWeatherData", "getWeatherData="+ JsonUtil.toJson(response.body()));
                    try {
                        JSONObject jsonObject = new JSONObject(JsonUtil.toJson(response.body()));
                        String json = jsonObject.optString("data");
                        WeatherInformationBean informationBean =(WeatherInformationBean) JsonUtil.parseJsonToBean(json, WeatherInformationBean.class);
                        if(!UIUtils.isEmpty(informationBean)){
                            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("weather_json",json);
                            if(loadView != null) loadView.setVisibility(View.GONE);
                            weatherInformationBean.setValue(informationBean);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }

                @Override
                public void onFailure(Call<Object> call, Throwable t) {
                    if(!UIUtils.isEmpty(t.getMessage()) &&t.getMessage().equals("timeout")) getWeatherData(lat,lng,loadView);
                    Log.d("getWeatherData", "error="+t.getMessage());
                }
            });
        }catch (Exception e){}

    }

    //获取yj
    public void getYJ(){
        //创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.wnl.tianqijun.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //创建网络请求接口实例
        BaseAppApi request = retrofit.create(BaseAppApi.class);
        HashMap<String, String> hashMap = new HashMap<>();
        retrofit2.Call<Object> call = request.getYJData(JmTools.encryptParams(hashMap, "Calendar.Yiji"));
        //发送网络请求(异步)
        call.enqueue(new Callback<Object>() {
            @Override
            public void onResponse(retrofit2.Call<Object> call, Response<Object> response) {
                Log.d("getYJData=4", "getYJData="+JsonUtil.toJson(response.body()));
                if(!UIUtils.isEmpty(response) && !UIUtils.isEmpty(response.body())){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            try {
                                YJDataBean yjDataBean = JsonUtil.parseJsonToBean(JsonUtil.toJson(response.body()),YJDataBean.class);
                                if(!UIUtils.isEmpty(yjDataBean) && !UIUtils.isEmpty(yjDataBean.getData())){
                                    DataSupport.deleteAll(YijiBean.class);
                                    DataSupport.saveAll(yjDataBean.getData());
                                    ACacheUtil.saveYijiData();
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }).start();
                }

            }

            @Override
            public void onFailure(Call<Object> call, Throwable t) {
            }
        });
    }

    //获取ss
    public void getSS(){
        //创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.wnl.tianqijun.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //创建网络请求接口实例
        BaseAppApi request = retrofit.create(BaseAppApi.class);
        HashMap<String, String> hashMap = new HashMap<>();
        retrofit2.Call<Object> call = request.getSSData(JmTools.encryptParams(hashMap, "Calendar.Shensha"));
        //发送网络请求(异步)
        call.enqueue(new Callback<Object>() {
            @Override
            public void onResponse(retrofit2.Call<Object> call, Response<Object> response) {
                Log.d("getSSData=4", "getSSData="+JsonUtil.toJson(response.body()));
                if(!UIUtils.isEmpty(response) && !UIUtils.isEmpty(response.body())){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            try {
                                SSDataBean ssDataBean = JsonUtil.parseJsonToBean(JsonUtil.toJson(response.body()),SSDataBean.class);
                                if(!UIUtils.isEmpty(ssDataBean) && !UIUtils.isEmpty(ssDataBean.getData())){
                                    DataSupport.deleteAll(ShenshaBean.class);
                                    DataSupport.saveAll(ssDataBean.getData());
                                    ACacheUtil.saveShenShaData();
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }).start();
                }
            }

            @Override
            public void onFailure(Call<Object> call, Throwable t) {
            }
        });

    }
}
